package com.es.action.classloader;

import com.es.common.Cache;
import com.es.util.file.FileUtil;

import java.io.*;

/**
 * 类加载器扩展
 *
 * @author Will
 */
public class ClassLoaderEx extends ClassLoader {

    private String targetClassesPath;

    public ClassLoaderEx() {
        this.targetClassesPath = (String) Cache.get("targetClassesPath");
    }

    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] classData = FileUtil.getFileData(className2Path(name));
        if (classData == null) {
            throw new ClassNotFoundException();
        } else {
            return defineClass(name, classData, 0, classData.length);
        }
    }

    /**
     * 获取 class文件路径
     *
     * @param className 类全名
     * @return 类所在文件路径
     */
    private String className2Path(String className) {
        return targetClassesPath + className.replace('.', File.separatorChar) + ".class";
    }
}
